package prj.carmap.mobile.activity;

import java.util.List;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.model.SellerType;
import prj.carmap.mobile.process.SellerByTypeProcess;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar.LayoutParams;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.miaowang.salad.activity.MineInfoActivity;

/**
 * 商家分类界面
 * 
 */
public class SellerTypeActivity extends SherlockActivity {

	final static String TAG = "SellerTypeActivity";

	private List<SellerType> sellerTypes;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		CarmapApplication.currentPage = "type";
		sellerTypes = CarmapApplication.sellerTypes;
		CarmapApplication.addActivity(this);
		setContentView(R.layout.activity_seller_type);

		// Inflate the custom view
		View customNav = LayoutInflater.from(this).inflate(R.layout.nav_view,
				null);
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		((TextView) customNav.findViewById(R.id.nav_title)).setText("分类");
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT, Gravity.CENTER);
		getSupportActionBar().setCustomView(customNav);
		customNav.setLayoutParams(lp);

		// ActionBarf返回按钮
		Button returnBtn = (Button) customNav.findViewById(R.id.return_prev);
		returnBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
					public void onClick(View v) {
						SellerTypeActivity.this.finish();
					}
				});
		initMenuItem();
		ListView listView = (ListView) findViewById(R.id.seller_type_list_view);
		listView.setAdapter(new SellerTypeListAdapter(sellerTypes));

		// listView.setOnItemClickListener(this);
	}

	@SuppressWarnings("deprecation")
	private void initMenuItem() {
		if ("type".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_type);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_type_image);
			itemImage.setImageResource(R.drawable.type_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_type_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		} 
//		else if ("search".equals(CarmapApplication.currentPage)) {
//			// 底部菜单项
//			View menuItem = this.findViewById(R.id.menu_item_search);
//			menuItem.setBackgroundDrawable(getApplication().getResources()
//					.getDrawable(R.drawable.bottom_background));
//			// 底部菜单图标
//			ImageView itemImage = (ImageView) this
//					.findViewById(R.id.item_search_image);
//			itemImage.setImageResource(R.drawable.search_select);
//			// 底部菜单文字
//			TextView itemText = (TextView) this
//					.findViewById(R.id.item_search_text);
//			itemText.setTextColor(getApplication().getResources().getColor(
//					R.color.white));
//		} 
		else if ("mine".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_mine);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_mine_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_mine_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}
		else if ("salad".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_salad);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_salad_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_salad_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}
		// else if ("more".equals(CarmapApplication.currentPage)) {
		// // 底部菜单项
		// View menuItem = this.findViewById(R.id.menu_item_more);
		// menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
		// // 底部菜单图标
		// ImageView itemImage = (ImageView)
		// this.findViewById(R.id.item_more_image);
		// itemImage.setImageResource(R.drawable.more_select);
		// // 底部菜单文字
		// TextView itemText = (TextView)
		// this.findViewById(R.id.item_more_text);
		// itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		// }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		View view = (View) this.findViewById(R.id.menu_item_home);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SellerTypeActivity.this.startActivity(new Intent(
						SellerTypeActivity.this, MainActivity.class));
				SellerTypeActivity.this.finish();
			}
		});
//		view = (View) this.findViewById(R.id.menu_item_search);
//		view.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(SellerTypeActivity.this,
//						SellerSearchActivity.class);
//				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				CarmapApplication.popView = new DialogView(
//						SellerTypeActivity.this);
//				CarmapApplication.popView.show();
//				SellerTypeActivity.this.startActivity(intent);
//			}
//		});

		view = (View) this.findViewById(R.id.menu_item_mine);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				UserInfo userInfo = CarmapApplication.getInstance().userInfo;
//				if (userInfo == null) {
//					SellerTypeActivity.this.startActivity(new Intent(
//							SellerTypeActivity.this, LoginActivity.class));
//				} else {
//					SellerTypeActivity.this.startActivity(new Intent(
//							SellerTypeActivity.this, ProfileActivity.class));
//				}
				SellerTypeActivity.this.startActivity(new Intent(
						SellerTypeActivity.this, MineInfoActivity.class));
			}
		});

		// view = (View) this.findViewById(R.id.menu_item_more);
		// view.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// SellerTypeActivity.this.startActivity(new
		// Intent(SellerTypeActivity.this, MoreActivity.class));
		// }
		//
		// });

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onResume() {
		super.onResume();
		CarmapApplication.currentPage = "type";
	}

	private class SellerTypeListAdapter extends BaseAdapter {
		View[] itemsView;

		public SellerTypeListAdapter(List<SellerType> list) {
			itemsView = new View[list.size()];
			for (int i = 0; i < list.size(); i++) {
				itemsView[i] = makeView(list.get(i));
			}
		}

		@Override
		public int getCount() {
			return itemsView.length;
		}

		@Override
		public Object getItem(int position) {
			return itemsView[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return itemsView[position];
		}

		@SuppressLint("NewApi")
		private View makeView(SellerType sellerType) {
			LayoutInflater inflater = (LayoutInflater) SellerTypeActivity.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View itemView = inflater.inflate(R.layout.listitem_seller_type,
					null);
			if (sellerType.typeName.equals("汽车救援维修")) {
				RelativeLayout rl = (RelativeLayout) itemView
						.findViewById(R.id.seller_type_list);
				rl.setBackgroundResource(R.drawable.auto_rescue_background);
				ImageView iv = (ImageView) itemView
						.findViewById(R.id.seller_type_icon);
				iv.setBackgroundResource(R.drawable.auto_rescue1);
				TextView name = (TextView) itemView
						.findViewById(R.id.seller_type_name);
				name.setText(sellerType.typeName);
			}
			if (sellerType.typeName.equals("汽车洗车")) {
				RelativeLayout rl = (RelativeLayout) itemView
						.findViewById(R.id.seller_type_list);
				rl.setBackgroundResource(R.drawable.wash_auto_background);
				ImageView iv = new ImageView(SellerTypeActivity.this);
				iv.setBackgroundResource(R.drawable.wash_auto1);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
				RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);  
				lp1.setMargins(0, 60, 0, 0);
				rl.addView(iv, lp1);
				TextView name = new TextView(SellerTypeActivity.this);
				RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);  
				lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);  
				lp2.setMargins(0, 18, 18, 0);
				name.setTextColor(getResources().getColor(R.color.white));
				name.setText(sellerType.typeName);
				rl.addView(name, lp2);
				
			}
			if (sellerType.typeName.equals("生活服务")) {
				RelativeLayout rl = (RelativeLayout) itemView
						.findViewById(R.id.seller_type_list);
				rl.setBackgroundResource(R.drawable.life_service_background);
				ImageView iv = new ImageView(SellerTypeActivity.this);
				iv.setBackgroundResource(R.drawable.life_service1);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
				RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				lp1.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);  
				lp1.setMargins(30, 40, 20, 0);
				rl.addView(iv, lp1);
				TextView name = new TextView(SellerTypeActivity.this);
				RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);  
				lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);  
				lp2.setMargins(0, 18, 18, 0);
				name.setTextColor(getResources().getColor(R.color.white));
				name.setText(sellerType.typeName);
				rl.addView(name, lp2);
			}
			GridView gridView = (GridView) itemView
					.findViewById(R.id.sub_seller_type_list);
			int count = Math.round(sellerType.children.size() / 2f);
			if (count < 3)
				count = 3;
			ViewGroup.LayoutParams lp = gridView.getLayoutParams();
			DisplayMetrics dm = new DisplayMetrics();
			dm = getResources().getDisplayMetrics();

			// float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
			lp.height = (int) (lp.height * count / 3);
			gridView.setLayoutParams(lp);
			if (sellerType.children != null) {
				gridView.setAdapter(new SubSellerAdapter(sellerType.children,
						SellerTypeActivity.this, gridView, 2));
			}
			return itemView;
		}

		private int max(int count1, int count2) {
			if (count1 > count2)
				return count1;
			return count2;
		}
	}
}

// 自定义适配器
class SubSellerAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private List<SellerType> sellerTypes;
	private Context context;
	private GridView gridView;
	private int cols;
	private int total = 0;

	public SubSellerAdapter(List<SellerType> sellerTypes, Context context,
			GridView gridView, int COLS) {
		super();
		this.sellerTypes = sellerTypes;
		this.context = context;
		this.gridView = gridView;
		this.cols = COLS;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		int size = sellerTypes.size();
		size = (size % 2 == 0) ? size : size + 1;
		return size >= 6 ? size : 6;
	}

	@Override
	public Object getItem(int position) {
		if (position < sellerTypes.size()) {
			return sellerTypes.get(position);
		}
		return new SellerType();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Button subTypeBtn = (Button) inflater.inflate(R.layout.sub_seller_type,
				null);
		if (position < sellerTypes.size()) {
			final SellerType sellerType = sellerTypes.get(position);
			subTypeBtn.setText(sellerType.typeName);
			subTypeBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.i("sss", "fghg");
					SellerByTypeProcess process = new SellerByTypeProcess();
					process.setContext(context);
					process.getSellerTypes(sellerType.typeId + "",
							sellerType.typeName);

				}
			});
		} else {
			subTypeBtn.setText("");
		}
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getResources().getDisplayMetrics();

		float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
		int rows = (getCount() + 1) / 2;
		ViewGroup.LayoutParams lp = gridView.getLayoutParams();
		AbsListView.LayoutParams params = new AbsListView.LayoutParams(
				(int) ((wm.getDefaultDisplay().getWidth() * 0.64 - 15 * density) / 2),
				(int) ((lp.height - 2 * density) / rows));
		subTypeBtn.setLayoutParams(params);
		return subTypeBtn;
	}

}
